import React from "react";
import PageTitle from 'component/page-title'
import CategorySelector from "./category-selector";
import FileUploader from "component/file-upload";
import RichEditor from "component/rich-editor"

import './save.scss'
import Product from "@/service/product-service.jsx";
import Mutils from "@/utils/index.jsx";

const _product = new Product();
const _mm = new Mutils();

class ProductSave extends React.Component {
    constructor(props) {
        super(props);
        this.state ={
            pid:this.props.match.params.pid,
            saveTitle:"添加",
            name:"",
            subtitle:"",
            categoryId:0,
            parentCategoryId:0,
            subImages:[],
            price:"",
            stock:"",
            detail:"",
            status:1 // 商品状态1在售
        }
    }
    componentWillMount(){
        if(this.state.pid) {
            this.setState({
                saveTitle:"修改"
            })
        }
    }
    componentDidMount(){
        this.loadProduct();
    }
    loadProduct(){
        // 有pid编辑，表单回填
        if(this.state.pid){
            _product.getProduct(this.state.pid).then(res => {
                res.data.subImages = res.data.subImages ? res.data.subImages.split(',').map(img => {
                    return {
                        uri:img,
                        url:res.data.imageHost + img
                    }
                }) : [];
                res.data.defaultDetail = res.data.detail;
                this.setState(res.data);
            },err => {
                _mm.errorTips(err);
            })
        }
    }
    onValueChange(e){
        const { name , value } = e.target;
        this.setState({
            [name]:(name === 'price' || name === 'stock') ? parseInt(value) : value.trim()
        })
    }
    // 品类选择器
    onCategoryChange(categoryId,parentCategoryId) {
        this.setState({
            categoryId,
            parentCategoryId
        })
    }
    // 上传图片成功
    onUploadSuccess(res) {
        if(res.status === 0){
            this.setState({
                subImages:[...this.state.subImages,res.data]
            })
        }
    }
    // 上传图片失败
    onUploadError(err){
        _mm.errorTips(err.message || '图片上传失败！');
    }
    onImageDelete(e) {
        let index = parseInt(e.target.getAttribute('index'));
        let subImages = this.state.subImages;
        subImages.splice(index,1);
        this.setState({
            subImages
        })
    }
    editValChange(value){
        this.setState({
            detail:value
        })
    }
    onSubmit(){
        let product = {
            name:this.state.name,
            subtitle:this.state.subtitle,
            categoryId:parseInt(this.state.categoryId),
            detail:this.state.detail,
            price:parseInt(this.state.price),
            stock:parseInt(this.state.stock),
            staus:this.state.status,
            subImages:this.state.subImages.map(img => img.uri).join(',')
        }
        let productCheckResult = _product.checkProduct(product);
        if(this.state.id) {
            product.id = this.state.id;
        }
        if(productCheckResult.status){
            _product.saveProduct(product).then(res => {
                _mm.successTips(res.data);
                this.props.history.push('/product/index');
            },err => {
                _mm.errorTips(err);
            })
        }else{
            _mm.errorTips(productCheckResult.msg);
        }
    }
    render() {
        const { name , subtitle ,price , stock ,categoryId , parentCategoryId ,detail,defaultDetail } = this.state;
        return (
            <div id="page-wrapper">
                <PageTitle title={this.state.saveTitle + "商品"} />
                <div className="form-horizontal">
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品名称</label>
                        <div className="col-sm-5">
                            <input 
                            type="text" 
                            className="form-control" 
                            placeholder="请输入商品名称" 
                            name="name"
                            value={name}
                            onChange={e => this.onValueChange(e)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品描述</label>
                        <div className="col-sm-5">
                            <input 
                            type="text" 
                            className="form-control" 
                            placeholder="请输入商品描述" 
                            name="subtitle"
                            value={subtitle}
                            onChange={e => this.onValueChange(e)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">所属分类</label>
                        <CategorySelector 
                            categoryId={categoryId}
                            parentCategoryId={parentCategoryId}
                            onCategoryChange={(categoryId,parentCategoryId) => this.onCategoryChange(categoryId,parentCategoryId)}
                        />
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品价格</label>
                        <div className="col-sm-3">
                            <div className="input-group">
                                <input 
                                type="number" 
                                min="0" 
                                className="form-control" 
                                placeholder="请输入商品价格" 
                                name="price"
                                value={price}
                                onChange={e => this.onValueChange(e)}
                                />
                                <span className="input-group-addon">元</span>
                            </div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品库存</label>
                        <div className="col-sm-3">
                            <div className="input-group">
                                <input 
                                type="number" 
                                min="0" 
                                className="form-control" 
                                placeholder="请输入商品库存" 
                                name="stock"
                                value={stock}
                                onChange={e => this.onValueChange(e)}
                                />
                                <span className="input-group-addon">件</span>
                            </div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品图片</label>
                        <div className="col-sm-10">
                            {
                                this.state.subImages.length ? this.state.subImages.map((v,index) => {
                                    return (
                                        <div className="imgWrapper" key={v.url}>
                                            <img src={v.url} />
                                            <i 
                                            className="fa fa-close" 
                                            index={index} 
                                            onClick={(e) => this.onImageDelete(e)}
                                            ></i>
                                        </div>
                                    )
                                }) : (<div>请选择图片</div>)
                            }
                        </div>
                        <div className="col-sm-offset-2 col-sm-10" style={{marginTop:'10px'}}>
                            <FileUploader 
                                onSuccess={(res) => this.onUploadSuccess(res)}
                                onError={(err) => this.onUploadError(err)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-sm-2 control-label">商品详情</label>
                        <div className="col-sm-10">
                            <RichEditor 
                                detail={detail}
                                defaultDetail={defaultDetail}
                                onValueChange={value => this.editValChange(value)}
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-sm-offset-2 col-sm-10">
                            <button 
                            type="button" 
                            className="btn btn-primary"
                            onClick={() => this.onSubmit()}
                            >确定</button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
export default ProductSave;